import react from '@vitejs/plugin-react-swc'
import path from 'path'
import { defineConfig } from 'vite'
import viteImagemin from 'vite-plugin-imagemin'
import { viteStaticCopy } from 'vite-plugin-static-copy'
import svgr from 'vite-plugin-svgr'
import { manualChunksPlugin } from 'vite-plugin-webpackchunkname'
import { proxyHost } from './proxys'

const apiRoutes = ['^/api/', '/health']
// Use environment variable to determine the target.
const isDev = process.env.NODE_ENV === 'development'
const target = isDev ? proxyHost : process.env.VITE_PROXY_TARGET || 'http://127.0.0.1:7860'
const proxyTargets = apiRoutes.reduce((proxyObj, route) => {
  proxyObj[route] = {
    target: `${target}`,
    changeOrigin: true,
    withCredentials: true,
    secure: false,
    ws: true
  }
  // 文件服务地址
  proxyObj['/bisheng'] = {
    target: `${target}:50061`,
    changeOrigin: true,
    withCredentials: true,
    secure: false
  }
  // swagger地址
  proxyObj['/docs'] = {
    target: `${target}`,
    changeOrigin: true,
    withCredentials: true,
    secure: false
  }
  proxyObj['/openapi.json'] = {
    target: `${target}`,
    changeOrigin: true,
    withCredentials: true,
    secure: false
  }
  return proxyObj
}, {})

export default defineConfig(() => {
  return {
    build: {
      outDir: 'build',
      rollupOptions: {
        onwarn(warning, defaultHandler) {
          if (warning.code === 'SOURCEMAP_ERROR') {
            return
          }
          defaultHandler(warning)
        },
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks: (id: string) => {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        }
      },
      minify: 'terser', // 启用 terser 压缩
      terserOptions: {
        compress: {
          pure_funcs: ['console.log'], // 只删除 console.log
          drop_debugger: true // 删除 debugger
        }
      }
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    },
    plugins: [
      manualChunksPlugin(),
      react(),
      svgr(),
      viteStaticCopy({
        targets: [
          {
            src: [
              'node_modules/ace-builds/src-min-noconflict/ace.js',
              'node_modules/ace-builds/src-min-noconflict/mode-json.js',
              'node_modules/ace-builds/src-min-noconflict/worker-json.js',
              'node_modules/ace-builds/src-min-noconflict/mode-yaml.js',
              'node_modules/ace-builds/src-min-noconflict/worker-yaml.js'
            ],
            dest: 'node_modules/ace-builds/src-min-noconflict/'
          },
          {
            src: 'node_modules/pdfjs-dist/build/pdf.worker.min.js',
            dest: './'
          }
        ]
      }),
      // 打包物体积报告
      // visualizer({
      //   open: true,
      // })
      /* 自动压缩图片 */
      viteImagemin({
        gifsicle: { optimizationLevel: 3 },
        optipng: { optimizationLevel: 7 },
        mozjpeg: { quality: 60 }, // 适度降低质量以换取更小的文件
        pngquant: { quality: [0.7, 0.8], speed: 4 }, // 略微牺牲质量换取更大的压缩
        svgo: {
          plugins: [
            { name: 'removeViewBox' }, // 可能需要保留视图框，根据实际情况决定
            { name: 'removeEmptyAttrs', active: false }
          ]
        }
      })
    ],
    css: {
      preprocessorOptions: {
        less: {
          math: 'always'
        }
      }
    },
    server: {
      host: '0.0.0.0',
      port: 3001,
      proxy: {
        ...proxyTargets
      },
      watch: {
        usePolling: true // 修复HMR热更新失效
      }
    }
  }
})
